package com.oracle.cmp.service;

import com.oracle.cmp.common.Constant;
import com.oracle.cmp.common.Result;
import com.oracle.cmp.entity.*;
import com.oracle.jdbc.util.Dao;

import java.time.LocalDateTime;
import java.util.*;

public class OrderServicelmpl implements OrderService {
    @Override
    public Result queryForPage(Map map, int pageNum) {
        String sql="SELECT orderid,ordercode,orderdate,orderflag,name FROM biz_order r LEFT OUTER JOIN sys_code c ON r.OrderFlag=c.code where 1=1";
        List params = new ArrayList();
        if(map.get("ordercode")!=null&&!"".equals(map.get("ordercode"))){
            sql += " and ordercode=?";
            params.add(map.get("ordercode"));
        }
        if(map.get("orderdate")!=null&&!"".equals(map.get("orderdate"))){
            sql += " and orderdate=?";
            params.add(map.get("orderdate"));
        }
        if(map.get("orderflag")!=null&&!"".equals(map.get("orderflag"))){
            sql += " and orderflag=?";
            params.add(map.get("orderflag"));
        }
        sql+=" limit ?,?";
        params.add((pageNum-1)* Constant.PAGESIZE);
        params.add(Constant.PAGESIZE);
        List<Order> list = Dao.query(sql,Order.class,params.toArray());
        return new Result(true,list,"查询成功");
    }

    @Override
    public Result save(Order order, List<OrderDetail> details, int userId) {
        //先查询订单编号是否已经存在
        String sql="select orderid,ordercode,orderdate,orderflag from biz_order  where ordercode=?";
        List<Order> list= Dao.query(sql,Order.class,order.getOrdercode());
        //如果存在
        if (list!=null&&list.size()>0){
            return new Result(false,null,"订单编号已存在！");
        }
        //循环details 判断每个配件的库存是否满足出库数量
        sql="select partsreqcount from biz_partsrepertory where partsid=?";
        for (OrderDetail orderDetail:details){
            List<PartsRepertory> listpre=Dao.query(sql,PartsRepertory.class,orderDetail.getPartsid());
            if (listpre==null||listpre.size()==0){
                //库存不满足订单出库，返回result
                return  new Result(false,null,"库存不足");
            }else {
                if (listpre.get(0).getPartsreqcount()<orderDetail.getOrderpartscount()){
                    return  new Result(false,null,"库存不足");
                }
            }
        }
        //插入订单主表，获得自增的主键id
        String sql1="ALTER TABLE biz_order auto_increment=1";
        Dao.executeSql(sql1);
        sql="insert into biz_order values(default,?,?,?)";
        int orderid=Dao.insert(sql,order.getOrdercode(),order.getOrderdate(),order.getOrderflag());

        String sql2="ALTER TABLE biz_orderdetail auto_increment=1";
        //循环details，插入明细表，orderid外键就是上面的自增主键
        sql="insert into biz_orderdetail values(default,?,?,?)";
     PartsRepetoryBillService partsRepetoryBillService=new PartsRepetoryBillImpl();
        for (OrderDetail orderDetail:details){
            Dao.executeSql(sql2);
            Dao.executeSql(sql,orderDetail.getPartsid(),orderid,orderDetail.getOrderpartscount());
            //调用出库业务处理
            Partsrepbill bill=new Partsrepbill();
            bill.setBillflag("out");
            bill.setBilltype("out1");
            bill.setBillcount(orderDetail.getOrderpartscount());
            bill.setPartsid(orderDetail.getPartsid());
            LocalDateTime time= LocalDateTime.now();
            bill.setBilltime(time);
          partsRepetoryBillService.save(bill);

        }
        return new Result(true,null,"保存成功");
    }

    public Result update(Order order,List<OrderDetail> details,String useid) {
//方法一：先删除原先的订单信息增加流水信息，并且恢复仓库数量
//        OrderService orderService=new OrderServicelmpl();
//        orderService.delete(orderId,useid);
//        //将现在的表内容存入
//        orderService.save(order,details,Integer.parseInt(useid));
//        return  new Result(true,null,"修改成功");

 //方法二:根据订单中的信息查出更改前的流水信息
        String sql="select orderdetailid,partsid,orderid,orderpartscount from biz_orderdetail where orderid=?";
        List<OrderDetail> orderDetails=Dao.query(sql,OrderDetail.class,order.getOrderid());

        //需要进行插入并出库的新的
        List<OrderDetail> addlist=new ArrayList();
        //原来有现在修改后没有了，需要进行删除，并入库的
        List<OrderDetail> inupdatelist=new ArrayList();
        //原来有现在也有，但数量变多了，需要进行出库处理
        List<OrderDetail> outupdatelist=new ArrayList();
        Map map=new HashMap();
//       //对比该流水和更改后的流水存在差异
      List <Integer>incount=new ArrayList();
      List <Integer>outcount=new ArrayList();
        for (OrderDetail orderDetail:orderDetails){
         map.put(orderDetail.getPartsid(),orderDetail.getOrderpartscount());
        }
        for (OrderDetail detail:details){
            if (map.get(detail.getPartsid())==null){
             addlist.add(detail);
            }
            if (map.get(detail.getPartsid())!=null){
                int count=(int)map.get(detail.getPartsid());
                if (detail.getOrderpartscount()>=count){
                    outupdatelist.add(detail);
                  outcount.add(detail.getOrderpartscount()-count);
                }else {
                    inupdatelist.add(detail);
                 incount.add(count-detail.getOrderpartscount());
                }
                map.remove(detail.getPartsid());
            }
        }

        PartsRepetoryBillService partsRepetoryBillService=new PartsRepetoryBillImpl();
        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            Integer key = (Integer)entry.getKey();
            Integer value = (Integer)entry.getValue();
                Partsrepbill bill=new Partsrepbill();
                bill.setBillflag("in");
                bill.setBilltype("in3");
                bill.setPartsid(key);
                bill.setBillcount(value);
                bill.setBilluser(useid);
                LocalDateTime time= LocalDateTime.now();
                bill.setBilltime(time);
                partsRepetoryBillService.save(bill);
            sql="delete from biz_orderdetail where orderid=? and partsid=?";
            Dao.executeSql(sql,order.getOrderid(),key);

//             return new Result(true,null,"删除成功");
            }

            String sql2="ALTER TABLE biz_orderdetail auto_increment=1";
            //循环details，插入明细表，orderid外键就是上面的自增主键
            sql="insert into biz_orderdetail values(default,?,?,?)";
            for (OrderDetail add:addlist){
                Dao.executeSql(sql2);
                Dao.executeSql(sql,add.getPartsid(),add.getOrderid(),add.getOrderpartscount());
                //调用出库业务处理
                Partsrepbill bill=new Partsrepbill();
                bill.setBillflag("out");
                bill.setBilltype("out1");
                bill.setBillcount(add.getOrderpartscount());
                bill.setPartsid(add.getPartsid());
                LocalDateTime time= LocalDateTime.now();
                bill.setBilltime(time);
                partsRepetoryBillService.save(bill);
            }

            for (int i=0;i<inupdatelist.size();i++){
               sql="update biz_orderdetail set orderpartscount=? where orderid=? and partsid=?";
               Dao.executeSql(sql,inupdatelist.get(i).getOrderpartscount(),inupdatelist.get(i).getOrderid(),inupdatelist.get(i).getPartsid());
               Partsrepbill bill=new Partsrepbill();
               bill.setBillflag("in");
               bill.setBilltype("in3");
               bill.setBillcount(incount.get(i));
               bill.setPartsid(inupdatelist.get(i).getPartsid());
               LocalDateTime time= LocalDateTime.now();
               bill.setBilltime(time);
               Dao.executeSql(sql2);
               partsRepetoryBillService.save(bill);
           }


            for (int i=0;i<outupdatelist.size();i++){
                sql="update biz_orderdetail set orderpartscount=? where orderid=? and partsid=?";;
                Dao.executeSql(sql,outupdatelist.get(i).getOrderpartscount(),outupdatelist.get(i).getOrderid(),outupdatelist.get(i).getPartsid());
                Partsrepbill bill=new Partsrepbill();
                bill.setBillflag("out");
                bill.setBilltype("out1");
                bill.setBillcount(outcount.get(i));
                bill.setPartsid(outupdatelist.get(i).getPartsid());
                LocalDateTime time= LocalDateTime.now();
                bill.setBilltime(time);
                Dao.executeSql(sql2);
                partsRepetoryBillService.save(bill);
            }

        return new Result(true,null,"订单修改成功！");
    }

    @Override
    public Result delete(int orderId, String userId) {
        //通过订单id 查询出明细
        String sql="select orderdetailid,partsid,orderid,orderpartscount from biz_orderdetail where orderid=?";
        List<OrderDetail> details=Dao.query(sql,OrderDetail.class,orderId);
        PartsRepetoryBillService partsRepetoryBillService=new PartsRepetoryBillImpl();

        for (OrderDetail detail:details){
            Partsrepbill bill=new Partsrepbill();
            bill.setBillflag("in");
            bill.setBilltype("in3");
            bill.setBillcount(detail.getOrderpartscount());
            bill.setPartsid(detail.getPartsid());
            bill.setBilluser(userId);
            LocalDateTime time= LocalDateTime.now();
            bill.setBilltime(time);
            partsRepetoryBillService.save(bill);
        }
        sql="delete from biz_orderdetail where orderId=?";

        Dao.executeSql(sql,orderId);

        sql="delete from biz_order where orderid=?";
        Dao.executeSql(sql,orderId);
        return new Result(true,null,"删除成功");
    }



    @Override
    public int count(Map<String, Object> map) {
        String sql="SELECT count(0) FROM (SELECT orderid,ordercode,orderdate,orderflag,name FROM biz_order r LEFT OUTER JOIN sys_code c ON r.OrderFlag=c.code where 1=1";
        List params = new ArrayList();
        if(map.get("ordercode")!=null&&!"".equals(map.get("ordercode"))){
            sql += " and ordercode=?";
            params.add(map.get("ordercode"));
        }
        if(map.get("orderdate")!=null&&!"".equals(map.get("orderdate"))){
            sql += " and orderdate=?";
            params.add(map.get("orderdate"));
        }
        if(map.get("orderflag")!=null&&!"".equals(map.get("orderflag"))){
            sql += " and orderflag=?";
            params.add(map.get("orderflag"));
        }
        sql+=")as a";
        int total = ((Long)Dao.queryOne(sql,params.toArray())[0]).intValue();
        return total;
    }



    @Override
    public Result queryForPage1(Map map, int pageNum) {
        String sql="SELECT orderid,ordercode,orderdate,orderflag,name FROM biz_order r LEFT OUTER JOIN sys_code c ON r.OrderFlag=c.code where 1=1";
        List params = new ArrayList();
        if(map.get("ordercode")!=null&&!"".equals(map.get("ordercode"))){
            sql += " and ordercode=?";
            params.add(map.get("ordercode"));
        }
        if(map.get("orderdate")!=null&&!"".equals(map.get("orderdate"))){
            sql += " and orderdate=?";
            params.add(map.get("orderdate"));
        }
        if(map.get("orderflag")!=null&&!"".equals(map.get("orderflag"))){
            sql += " and orderflag=?";
            params.add(map.get("orderflag"));
        }
        sql+=" and orderflag NOT in(1)";
        sql+=" limit ?,?";
        params.add((pageNum-1)* Constant.PAGESIZE);
        params.add(Constant.PAGESIZE);
        List<Order> list = Dao.query(sql,Order.class,params.toArray());
        return new Result(true,list,"查询成功");
    }

    @Override
    public int count1(Map<String, Object> map) {
        String sql="SELECT count(0) FROM (SELECT orderid,ordercode,orderdate,orderflag,name FROM biz_order r LEFT OUTER JOIN sys_code c ON r.OrderFlag=c.code where 1=1";
        List params = new ArrayList();
        if(map.get("ordercode")!=null&&!"".equals(map.get("ordercode"))){
            sql += " and ordercode=?";
            params.add(map.get("ordercode"));
        }
        if(map.get("orderdate")!=null&&!"".equals(map.get("orderdate"))){
            sql += " and orderdate=?";
            params.add(map.get("orderdate"));
        }
        if(map.get("orderflag")!=null&&!"".equals(map.get("orderflag"))){
            sql += " and orderflag=?";
            params.add(map.get("orderflag"));
        }
        sql+=" and orderflag NOT in(1))as a";
        int total = ((Long)Dao.queryOne(sql,params.toArray())[0]).intValue();
        return total;
    }
    public Result selectById(int orderid) {
        Order order = Dao.queryOne("select * from biz_order where orderid = ?",Order.class,orderid);
        return new Result(true,order,"查询成功");
    }


}
